package com.lyw.springCloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther liyawei
 * @Date 2022/4/23 10:51
 */
@Component
public class LoadBalancerImpl implements LoadBalancer {

    // 原子类
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        // 1 % 2 = 1
        // 2 % 2 = 0
        // 3 % 2 = 1
        // 4 % 2 = 0
        // 5 % 2 = 1
        int index = getAndIncrement() % serviceInstances.size();

        // 根据访问的次数决定选取哪个服务器
        return serviceInstances.get(index);
    }

    // 求出客户端第几次访问当前请求
    private final int getAndIncrement() {
        int current = 0;
        int next = 0;
        do {
            current = atomicInteger.get();
            next = current > Integer.MAX_VALUE ? 0 : current + 1;
        } while(!atomicInteger.compareAndSet(current, next));
        System.out.println("第几次访问的次数： -> " + current);
        System.out.println("第几次访问的次数： -> " + next);
        return next;
    }
}
